<template>
  <UserLayout :active-index="activeIndex" :active-menu="activeMenu">
    <div class="publish-house-content">
      <div class="publish-wrapper">
        <!-- 主内容区域 -->
          <div class="publish-header">
            <h2>发布新房源</h2>

          </div>

          <el-steps :active="currentStep" finish-status="success" simple class="publish-steps">
            <el-step title="房源审核" />
            <el-step title="审核状态" />
            <el-step title="房源信息" />
            <el-step title="位置信息" />
          </el-steps>
          <!-- 步骤1: 提交审核 -->
          <div v-show="currentStep === 0" class="step-content">
            <div class="review-section">
              <h3>房源信息审核</h3>

              <el-form
                  :model="certificateInfo"
                  :rules="certificateRules"
                  ref="certificateFormRef"
                  label-width="120px"
                  class="certificate-form"
              >
                <el-form-item label="房产证编号" prop="certificateNumber">
                  <el-input
                      v-model="certificateInfo.certificateNumber"
                      placeholder="请输入房产证编号（示例：粤2023A1234567）"
                      @blur="handleCertificateNumberBlur"
                      clearable
                      class="certificate-number-input"
                  />

                  <!-- 提交新认证按钮 -->
                  <div v-if="certificateInfo.certificateNumber" class="new-certification-hint">
                    <el-button
                        type="text"
                        size="small"
                        @click="clearCertificateNumber"
                        class="clear-btn"
                    >
                      <el-icon><Refresh /></el-icon>
                      提交新认证
                    </el-button>
                  </div>

                  <p class="form-tip">格式：省份简称(1位)+年份(4位)+编号(7-14位数字或字母)，长度12-19字符</p>
                </el-form-item>

                <el-form-item label="房产证图片" prop="certificateImage">
                  <el-upload
                      action="#"
                      list-type="picture-card"
                      :auto-upload="false"
                      :file-list="certificateImages"
                      :on-change="handleCertificateImageChange"
                      :on-remove="handleCertificateImageRemove"
                      :limit="1"
                  >
                    <el-icon><Plus /></el-icon>
                  </el-upload>
                  <p class="upload-tip">请上传房产证照片，支持JPG、PNG格式</p>
                </el-form-item>

                <el-form-item label="房产地址" prop="propertyAddress">
                  <div class="address-selector">
                    <!-- 省份选择 -->
                    <el-select
                        v-model="certificateInfo.province"
                        placeholder="请选择省份"
                        @change="handleProvinceChange"
                        style="width: 120px; margin-right: 10px;"
                    >
                      <el-option
                          v-for="province in provinces"
                          :key="province.value"
                          :label="province.label"
                          :value="province.value"
                      />
                    </el-select>

                    <!-- 城市选择 -->
                    <el-select
                        v-model="certificateInfo.city"
                        placeholder="请选择城市"
                        @change="handleCityChange"
                        style="width: 120px; margin-right: 10px;"
                        :disabled="!certificateInfo.province"
                    >
                      <el-option
                          v-for="city in cities"
                          :key="city.value"
                          :label="city.label"
                          :value="city.value"
                      />
                    </el-select>

                    <!-- 区县选择 -->
                    <el-select
                        v-model="certificateInfo.district"
                        placeholder="请选择区县"
                        @change="handleDistrictChange"
                        style="width: 120px; margin-right: 10px;"
                        :disabled="!certificateInfo.city"
                    >
                      <el-option
                          v-for="district in districts"
                          :key="district.value"
                          :label="district.label"
                          :value="district.value"
                      />
                    </el-select>
                  </div>

                  <!-- 详细地址输入 -->
                  <el-input
                      v-model="certificateInfo.detailAddress"
                      placeholder="请输入详细地址（如：学府大道999号1栋1单元101室）"
                      @input="handleDetailAddressChange"
                      style="margin-top: 10px;"
                  />

                  <!-- 完整地址显示 -->
                  <div v-if="certificateInfo.propertyAddress" class="address-preview">
                    <span class="address-label">完整地址：</span>
                    <span class="address-text">{{ certificateInfo.propertyAddress }}</span>
                  </div>

                  <p class="form-tip">请先选择省市区，再输入详细地址信息</p>
                </el-form-item>

                <el-form-item label="房产信息" prop="propertyInfo">
                  <el-input
                      v-model="certificateInfo.propertyInfo"
                      placeholder="请输入房产信息（如面积、户型等）"
                      type="textarea"
                      :rows="3"
                  />
                </el-form-item>
              </el-form>

              <div class="submit-section">
                <el-checkbox v-model="agreementAccepted">
                  我已阅读并同意
                  <el-button type="text" @click="showAgreement">《房源发布协议》</el-button>
                </el-checkbox>

                <div class="submit-buttons">
                  <el-button
                      type="primary"
                      @click="nextStep"
                      :loading="submitting"
                  >
                    提交审核
                  </el-button>
                </div>
              </div>
            </div>
          </div>
          <!-- 步骤2: 审核状态 -->
          <div v-show="currentStep === 1" class="step-content">
            <!-- 待审核状态 -->
            <div v-if="verifyStatus === 0" class="review-pending-section">
              <div class="review-icon">
                <el-icon class="icon"><Clock /></el-icon>
              </div>
              <h3>您的房产信息正在审核中</h3>
              <p>管理员将在1-15个工作日内完成审核，请耐心等待</p>
              <p class="review-id">房产验证ID: {{ reviewId }}</p>

              <div class="review-progress">
                <el-progress :percentage="reviewProgress" status="warning" />
              </div>

              <div class="review-actions">
                <el-button @click="checkReviewStatus" :loading="isCheckingStatus">
                  {{ isCheckingStatus ? '查询中...' : '查询审核状态' }}
                </el-button>
                <el-button v-if="verifyStatus === 0" type="text" @click="cancelReview">取消审核</el-button>
              </div>


            </div>

            <!-- 审核通过状态 -->
            <div v-else-if="verifyStatus === 1" class="review-success-section">
              <div class="review-icon success">
                <el-icon class="icon"><Check /></el-icon>
              </div>
              <h3>恭喜！房产认证审核通过</h3>
              <p>您的房产信息已通过审核，现在可以继续发布房源信息</p>
              <p class="review-id">房产验证ID: {{ reviewId }}</p>

              <div class="review-progress">
                <el-progress :percentage="100" status="success" />
              </div>

              <div class="review-actions">
                <el-button type="primary" @click="nextStep">继续下一步</el-button>
                <el-button @click="checkReviewStatus">刷新状态</el-button>
              </div>
            </div>

            <!-- 审核被驳回状态 -->
            <div v-else-if="verifyStatus === 2" class="review-rejected-section">
              <div class="review-icon rejected">
                <el-icon class="icon"><Close /></el-icon>
              </div>
              <h3>很抱歉，房产认证审核未通过</h3>
              <p>请根据以下提示修改后重新提交申请</p>
              <p class="review-id">审核编号: {{ reviewId }}</p>

              <!-- 显示拒绝原因 -->
              <div v-if="rejectReason" class="reject-reason-box">
                <h4>驳回原因：</h4>
                <p class="reject-reason-text">{{ rejectReason }}</p>
              </div>

              <div class="review-progress">
                <el-progress :percentage="0" status="exception" />
              </div>

              <div class="review-actions">
                <el-button @click="queryRejectReason">查看详细原因</el-button>
                <el-button type="primary" @click="currentStep = 0">重新提交</el-button>
                <el-button @click="checkReviewStatus">刷新状态</el-button>
              </div>
            </div>

            <!-- 审核已取消状态 -->
            <div v-else-if="verifyStatus === 3" class="review-cancelled-section">
              <div class="review-icon cancelled">
                <el-icon class="icon"><Warning /></el-icon>
              </div>
              <h3>房产认证审核已取消</h3>
              <p>您已主动取消了房产认证审核，可以重新提交申请</p>
              <p class="review-id">审核编号: {{ reviewId }}</p>

              <div class="review-progress">
                <el-progress :percentage="0" status="warning" />
              </div>

              <div class="review-actions">
                <el-button type="primary" @click="currentStep = 0">重新提交</el-button>
                <el-button @click="checkReviewStatus">刷新状态</el-button>
              </div>
            </div>
          </div>

          <div v-if="currentStep >= 2" class="publish-content">
            <!-- 步骤1: 基本信息 -->
            <div v-show="currentStep === 2" class="step-content">
              <div class="house-info-container">
                <!-- 左侧表单区域 -->
                <div class="form-section">
                  <el-form
                      :model="houseInfo"
                      :rules="houseInfoRules"
                      ref="houseInfoFormRef"
                      label-width="120px"
                      class="house-form"
                  >
                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="房源标题" prop="houseTitle">
                      <el-input
                          v-model="houseInfo.houseTitle"
                          placeholder="请输入房源标题"
                          maxlength="50"
                          show-word-limit
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="联系电话" prop="phone">
                      <el-input
                          v-model="houseInfo.phone"
                          placeholder="请输入联系电话"
                          maxlength="11"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="户型" prop="layout">
                      <el-select
                          v-model="houseInfo.layout"
                          placeholder="请选择户型"
                          style="width: 100%"
                      >
                        <el-option label="一居室" :value="1" />
                        <el-option label="两居室" :value="2" />
                        <el-option label="三居室" :value="3" />
                        <el-option label="四居室" :value="4" />
                        <el-option label="五居室" :value="5" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="朝向" prop="orientation">
                      <el-select
                          v-model="houseInfo.orientation"
                          placeholder="请选择朝向"
                          style="width: 100%"
                      >
                        <el-option label="东" value="东" />
                        <el-option label="西" value="西" />
                        <el-option label="南" value="南" />
                        <el-option label="北" value="北" />
                        <el-option label="东南" value="东南" />
                        <el-option label="东北" value="东北" />
                        <el-option label="西南" value="西南" />
                        <el-option label="西北" value="西北" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="楼层" prop="floor">
                      <el-input
                          v-model="houseInfo.floor"
                          placeholder="例如: 5/18 (第5层,共18层)"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="面积(㎡)" prop="area">
                      <el-input-number
                          v-model="houseInfo.area"
                          :min="10"
                          :max="1000"
                          :precision="1"
                          style="width: 100%"
                          placeholder="请输入房屋面积"
                      />
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="租金(元/月)" prop="rent">
                      <el-input-number
                          v-model="houseInfo.rent"
                          :min="1"
                          :max="100000"
                          :precision="2"
                          style="width: 100%"
                          placeholder="请输入租金"
                      />
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="支付方式" prop="paymentType">
                      <el-select
                          v-model="houseInfo.paymentType"
                          placeholder="请选择支付方式"
                          style="width: 100%"
                      >
                        <el-option label="月付" :value="1" />
                        <el-option label="季付" :value="2" />
                        <el-option label="年付" :value="3" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-row>

                <el-row :gutter="20">
                  <el-col :span="12">
                    <el-form-item label="押金类型" prop="depositType">
                      <el-select
                          v-model="houseInfo.depositType"
                          placeholder="请选择押金类型"
                          style="width: 100%"
                      >
                        <el-option label="押1付1" :value="1" />
                        <el-option label="押1付3" :value="2" />
                        <el-option label="年押金" :value="3" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="出租类型" prop="rentType">
                      <el-radio-group v-model="houseInfo.rentType">
                        <el-radio :label="1">房东直售</el-radio>
                        <el-radio :label="2">中介代理</el-radio>
                      </el-radio-group>
                    </el-form-item>
                  </el-col>
                </el-row>



                <el-form-item label="房源简介" prop="houseSummary">
                  <el-input
                      v-model="houseInfo.houseSummary"
                      placeholder="请输入房源简介"
                      type="textarea"
                      :rows="4"
                      maxlength="500"
                      show-word-limit
                  />
                </el-form-item>

                <!-- 配套设施 -->
                <el-form-item label="配套设施">
                  <div class="facilities-grid">
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasFridge">冰箱</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasBed">床</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasWasher">洗衣机</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasWaterHeater">热水器</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasWifi">WiFi</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasSofa">沙发</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasKitchen">厨房</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasRangeHood">油烟机</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasGasStove">燃气灶</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasTV">电视</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasAirConditioner">空调</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasCloset">衣柜</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasSmartDoorLock">智能门锁</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasBalcony">阳台</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasCentralHeating">集中供暖</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasCupBoard">橱柜</el-checkbox>
                    <el-checkbox v-model="houseInfo.complementaryFacilities.hasDiningTable">餐桌</el-checkbox>
                  </div>
                </el-form-item>

                <!-- 房源图片上传 -->
                <el-form-item label="房源图片">
                  <el-upload
                      action="#"
                      list-type="picture-card"
                      :auto-upload="false"
                      :file-list="houseImages"
                      :on-change="handleImageChange"
                      :on-remove="handleImageRemove"
                      multiple
                      :limit="10"
                  >
                    <el-icon><Plus /></el-icon>
                  </el-upload>
                  <p class="upload-tip">最多可上传10张图片，建议尺寸1920*1080，支持JPG、PNG格式</p>
                </el-form-item>

                <!-- 封面图片选择 -->
                <el-form-item label="封面图片" v-if="houseImages.length > 0">
                  <div class="cover-image-selector">
                    <div
                        v-for="(image, index) in houseImages"
                        :key="index"
                        class="cover-image-item"
                        :class="{ active: coverImageIndex === index }"
                        @click="selectCoverImage(index)"
                    >
                      <img :src="image.url" alt="房源图片">
                      <div class="cover-badge" v-if="coverImageIndex === index">封面</div>
                    </div>
                  </div>
                  <p class="cover-tip">点击选择封面图片</p>
                </el-form-item>
              </el-form>
                </div>

                <!-- 右侧提示信息 -->
                <div class="tips-section">
                  <el-card class="tip-card">
                    <template #header>
                      <span class="tip-title">💡 配套设施提示</span>
                    </template>
                    <div class="tip-content">
                      <p><strong>基础设施：</strong>冰箱、洗衣机、热水器、WiFi</p>
                      <p><strong>家具用品：</strong>床、沙发、衣柜、餐桌</p>
                      <p><strong>厨房设备：</strong>厨房、油烟机、燃气灶、橱柜</p>
                      <p><strong>其他设施：</strong>电视、空调、智能门锁、阳台、集中供暖</p>
                      <div class="tip-note">
                        <el-icon><Warning /></el-icon>
                        <span>请如实选择房源配套设施，虚假信息可能导致投诉</span>
                      </div>
                    </div>
                  </el-card>

                  <el-card class="tip-card">
                    <template #header>
                      <span class="tip-title">📋 填写建议</span>
                    </template>
                    <div class="tip-content">
                      <ul>
                        <li>房源标题要简洁明了，突出亮点</li>
                        <li>租金设置要合理，参考周边价格</li>
                        <li>联系电话保持畅通，便于租客联系</li>
                        <li>房源简介详细描述房屋特色</li>
                      </ul>
                    </div>
                  </el-card>

                  <el-card class="tip-card">
                    <template #header>
                      <span class="tip-title">📸 图片建议</span>
                    </template>
                    <div class="tip-content">
                      <ul>
                        <li>上传真实清晰的房源照片</li>
                        <li>包含客厅、卧室、厨房、卫生间</li>
                        <li>选择光线充足的时间拍摄</li>
                        <li>避免过度美化，保持真实性</li>
                      </ul>
                    </div>
                  </el-card>
                </div>
              </div>
            </div>

            <!-- 步骤2: 位置信息 -->
            <div v-show="currentStep === 3" class="step-content">
              <div class="map-section">
                <div class="map-header">
                  <h3>选择房源位置</h3>
                  <p>请在地图上点击选择房源的具体位置，并填写相关信息</p>
                  <div class="location-actions">
                    <el-button
                      type="primary"
                      @click="getCurrentLocation"
                      :loading="locating"
                      size="small"
                    >
                      <el-icon><Location /></el-icon>
                      定位到当前位置
                    </el-button>
                  </div>
                </div>

                <!-- 位置信息表单 -->
                <el-form :model="locationInfo" label-width="120px" class="location-form">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <el-form-item label="房源位置" required>
                        <el-input
                            v-model="locationInfo.houseLocation"
                            placeholder="请输入房源位置描述，如：天河区珠江新城"
                            maxlength="100"
                            show-word-limit
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="交通信息">
                        <el-input
                            v-model="locationInfo.subwayInfo"
                            placeholder="如：地铁1号线天河站500米，公交站100米"
                            maxlength="100"
                            show-word-limit
                        />
                      </el-form-item>
                    </el-col>
                  </el-row>
                </el-form>

                <!-- 地图容器 -->
                <div id="map-container" style="width: 100%; height: 500px; border: 1px solid #ddd; border-radius: 8px; margin: 20px 0;"></div>

                <!-- 选中位置信息显示 -->
                <div v-if="selectedPosition" class="position-info">
                  <h4>已选择位置：</h4>
                  <div class="position-details">
                    <p><strong>经度:</strong> {{ selectedPosition.longitude.toFixed(6) }}</p>
                    <p><strong>纬度:</strong> {{ selectedPosition.latitude.toFixed(6) }}</p>
                    <p><strong>地址:</strong> {{ selectedPosition.address }}</p>
                  </div>
                </div>

                <div class="map-instructions">
                  <p>点击地图选择房源位置，可拖拽标记调整位置</p>
                  <p class="warning-text">注意：请确保选择的位置准确，这将影响房源的搜索和展示</p>
                </div>

                <!-- 确认发布按钮 -->
                <div class="publish-actions">
                  <el-button
                      type="primary"
                      size="large"
                      @click="confirmPublish"
                      :loading="publishing"
                      :disabled="!selectedPosition"
                      class="publish-btn"
                  >
                    <el-icon><Check /></el-icon>
                    确认发布房源
                  </el-button>
                  <el-button
                      @click="clearSelection"
                      :disabled="!selectedPosition"
                      class="clear-btn"
                  >
                    <el-icon><Refresh /></el-icon>
                    重新选择位置
                  </el-button>
                </div>

              </div>
            </div>









          <div v-if="currentStep > 0 && currentStep < 3" class="form-navigation">
            <el-button
                @click="() => currentStep--"
                :disabled="submitting"
            >
              上一步
            </el-button>
            <el-button
                v-if="currentStep < 3"
                type="primary"
                @click="() => nextStep()"
                :disabled="submitting"
            >
              下一步
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </UserLayout>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import UserLayout from '@/components/layout/UserLayout.vue'
import {
  Plus,
  Clock,
  Check,
  Close,
  Warning,
  Refresh,
  Location
} from '@element-plus/icons-vue'
import { uploadImageToOSS } from '@/utils/oss'
import {
  submitPropertyVerification,
  getPropertyVerifyStatus,
  getPropertyVerifyRefuseReason,
  cancelPropertyVerify,
  getPropertyVerificationByUserId,
  publishHouse
} from '@/utils/apiService'
import { checkLoginStatus } from '@/utils/auth'
import { province_object } from '@/utils/regions/province_object.js'
import { city_object } from '@/utils/regions/city_object.js'
import { country_object } from '@/utils/regions/country_object.js'

const router = useRouter()
const activeMenu = ref('publish-house')
const activeIndex = ref('3')
const currentStep = ref(0)
const submitting = ref(false)
const agreementAccepted = ref(false)
const mapSearchKeyword = ref('')
const selectedPosition = ref(null)
const coverImageIndex = ref(0)
const locating = ref(false)

// 表单引用
const certificateFormRef = ref()
const houseInfoFormRef = ref()

// 房产证信息
const certificateInfo = ref({
  certificateNumber: '',
  propertyAddress: '',
  propertyInfo: '',
  province: '',
  city: '',
  district: '',
  detailAddress: ''
})

// 房产证图片
const certificateImages = ref([])

// 省市区数据 - 使用完整的全国地域数据
const provinces = ref(Object.values(province_object).map(item => ({
  value: item.name,
  label: item.name,
  id: item.id
})))

const cities = ref([])
const districts = ref([])

// 获取城市数据的函数
const getCitiesByProvince = (provinceName) => {
  // 从city_object中筛选出属于指定省份的城市
  const cityList = Object.values(city_object).filter(city => city.province === provinceName)
  return cityList.map(item => ({
    value: item.name,
    label: item.name,
    id: item.id
  }))
}

// 获取区县数据的函数
const getDistrictsByCity = (cityName) => {
  // 从country_object中筛选出属于指定城市的区县
  const districtList = Object.values(country_object).filter(district => district.city === cityName)
  return districtList.map(item => ({
    value: item.name,
    label: item.name,
    id: item.id
  }))
}



// 已使用新的地域数据结构，原有数据已移除

// 自定义验证函数 - 检查详细地址是否填写
const validateDetailAddress = (rule, value, callback) => {
  if (!certificateInfo.value.detailAddress || certificateInfo.value.detailAddress.trim() === '') {
    callback(new Error('请输入详细地址'))
  } else {
    callback()
  }
}

// 房产证表单验证规则
const certificateRules = {
  certificateNumber: [
    { required: true, message: '请输入房产证编号', trigger: 'blur' },
    {
      pattern: /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}[0-9]{4}[0-9A-Za-z]{7,14}$/,
      message: '房产编号格式错误，应为：省份简称(1位)+年份(4位)+编号(7-14位数字或字母)，示例：粤2023A1234567',
      trigger: 'blur'
    },
    {
      min: 12,
      max: 19,
      message: '房产编号长度必须在12-19个字符之间',
      trigger: 'blur'
    }
  ],
  propertyAddress: [
    { required: true, message: '请输入房产地址', trigger: 'blur' },
    { validator: validateDetailAddress, trigger: 'blur' }
  ]
}

// 省市区选择处理函数
const handleProvinceChange = (value) => {
  certificateInfo.value.province = value
  certificateInfo.value.city = ''
  certificateInfo.value.district = ''
  cities.value = getCitiesByProvince(value)
  districts.value = []
  updatePropertyAddress()
}

const handleCityChange = (value) => {
  certificateInfo.value.city = value
  certificateInfo.value.district = ''
  districts.value = getDistrictsByCity(value)
  updatePropertyAddress()
}

const handleDistrictChange = (value) => {
  certificateInfo.value.district = value
  updatePropertyAddress()
}

const handleDetailAddressChange = () => {
  updatePropertyAddress()
}

// 清空房产证编号，用于提交新认证
const clearCertificateNumber = () => {
  certificateInfo.value.certificateNumber = ''
  verifyStatus.value = null
  reviewProgress.value = 0
  currentStep.value = 0
  localStorage.removeItem('savedCertificateNumber')
  ElMessage.info('已清空，您可以输入新的房产证编号提交认证')
}

// 处理房产证编号失焦事件
const handleCertificateNumberBlur = async () => {
  const certificateNumber = certificateInfo.value.certificateNumber
  if (certificateNumber && certificateNumber.trim()) {
    // 开发者模式下跳过认证检查
    if (developerMode.value) {
      ElMessage.success('🔧 开发者模式：跳过房产认证检查，直接进入下一步')
      verifyStatus.value = 1 // 模拟审核通过
      reviewId.value = 'DEV-' + Date.now()
      currentStep.value = 1 // 跳转到审核状态页面
      return
    }

    // 检查格式是否正确
    const pattern = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼]{1}[0-9]{4}[0-9A-Za-z]{7,14}$/
    if (pattern.test(certificateNumber) && certificateNumber.length >= 12 && certificateNumber.length <= 19) {
      // 格式正确，检查是否已有审核记录
      await checkExistingVerification(certificateNumber)
    }
  }
}

// 检查是否已有审核记录
const checkExistingVerification = async (certificateNumber) => {
  try {
    const response = await getPropertyVerifyStatus(certificateNumber)

    if (response.data.code === '200') {
      const statusValue = response.data.data
      verifyStatus.value = statusValue

      // 根据状态给出提示
      switch (statusValue) {
        case 0:
          ElMessage.info('检测到该房产证已提交审核，正在审核中')
          reviewProgress.value = 50
          currentStep.value = 1 // 跳转到审核状态页面
          startAutoStatusCheck()
          break
        case 1:
          ElMessage.success('检测到该房产证审核已通过，可以继续发布房源')
          reviewProgress.value = 100
          // 审核通过状态不自动跳转到审核状态页面，让用户手动查看或直接发布
          break
        case 2:
          ElMessage.warning('检测到该房产证审核未通过，请查看驳回原因')
          reviewProgress.value = 0
          // 审核驳回状态不自动跳转到审核状态页面，让用户重新提交
          await fetchRejectReasonSilently()
          break
        case 3:
          ElMessage.info('检测到该房产证审核已取消，可以重新提交')
          reviewProgress.value = 0
          break
      }
    }
  } catch (error) {
    // 如果是404错误，说明没有审核记录，这是正常的
    if (error.response?.status === 404) {
      console.log('该房产证编号暂无审核记录')
    } else {
      console.error('检查审核记录失败:', error)
    }
  }
}

// 更新完整地址
const updatePropertyAddress = () => {
  const { province, city, district, detailAddress } = certificateInfo.value
  certificateInfo.value.propertyAddress = `${province}${city}${district}${detailAddress}`
}

// 自定义验证函数 - 检查房产证图片是否上传
const validateCertificateImages = (rule, value, callback) => {
  if (certificateImages.value.length === 0) {
    callback(new Error('请上传房产证图片'))
  } else {
    callback()
  }
}

// 房源基本信息
// 房源信息 - 根据HouseRequest类重新设计
const houseInfo = ref({
  houseTitle: '',           // 房源标题
  houseSummary: '',         // 房源简介
  layout: null,             // 户型（1=一居室，2=两居室，3=三居室，4=四居室，5=五居室）
  floor: '',                // 楼层格式：所在楼层/总楼层
  area: null,               // 面积（平方米）
  orientation: '',          // 朝向
  phone: '',                // 联系电话
  rent: null,               // 租金（元/月）
  paymentType: null,        // 支付方式（1=月付，2=季付，3=年付）
  rentType: null,           // 出租类型（1=房东直售，2=中介代理）
  depositType: null,        // 押金类型（1=押1付1，2=押1付3，3=年押金）
  complementaryFacilities: {
    // 配套设施 - 根据ComplementaryFacilities类
    hasFridge: false,           // 冰箱
    hasBed: false,              // 床
    hasWasher: false,           // 洗衣机
    hasWaterHeater: false,      // 热水器
    hasWifi: false,             // WiFi
    hasSofa: false,             // 沙发
    hasKitchen: false,          // 厨房
    hasRangeHood: false,        // 油烟机
    hasGasStove: false,         // 燃气灶
    hasTV: false,               // 电视
    hasAirConditioner: false,   // 空调
    hasCloset: false,           // 衣柜
    hasSmartDoorLock: false,    // 智能门锁
    hasBalcony: false,          // 阳台
    hasCentralHeating: false,   // 集中供暖
    hasCupBoard: false,         // 橱柜
    hasDiningTable: false       // 餐桌
  }
})

// 房源类型选项
const houseTypes = [
  { value: 'apartment', label: '公寓' },
  { value: 'villa', label: '别墅' },
  { value: 'shared', label: '合租' },
  { value: 'whole', label: '整租' }
]

// 表单验证规则 - 根据HouseRequest类重新设计
const houseInfoRules = {
  houseTitle: [
    { required: true, message: '房源标题不能为空', trigger: 'blur' }
  ],
  houseSummary: [
    { required: true, message: '房源简介不能为空', trigger: 'blur' }
  ],
  layout: [
    { required: true, message: '户型不能为空', trigger: 'change' },
    { type: 'number', min: 1, max: 5, message: '户型必须为有效值', trigger: 'change' }
  ],
  floor: [
    { required: true, message: '楼层不能为空', trigger: 'blur' },
    { pattern: /^\d+\/\d+$/, message: '楼层格式错误，应为：所在楼层/总楼层', trigger: 'blur' }
  ],
  area: [
    { required: true, message: '面积不能为空', trigger: 'blur' },
    { type: 'number', min: 10, max: 1000, message: '面积必须在10-1000平方米之间', trigger: 'blur' }
  ],
  orientation: [
    { required: true, message: '朝向不能为空', trigger: 'change' }
  ],
  phone: [
    { required: true, message: '联系电话不能为空', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号码格式错误', trigger: 'blur' }
  ],
  rent: [
    { required: true, message: '租金不能为空', trigger: 'blur' },
    { type: 'number', min: 0.01, message: '租金必须大于0', trigger: 'blur' }
  ],
  paymentType: [
    { required: true, message: '支付方式不能为空', trigger: 'change' },
    { type: 'number', min: 1, max: 3, message: '支付方式必须为有效值', trigger: 'change' }
  ],
  rentType: [
    { required: true, message: '出租类型不能为空', trigger: 'change' },
    { type: 'number', min: 1, max: 2, message: '出租类型必须为有效值', trigger: 'change' }
  ],
  depositType: [
    { required: true, message: '押金类型不能为空', trigger: 'change' },
    { type: 'number', min: 1, max: 3, message: '押金类型必须为有效值', trigger: 'change' }
  ]
}



// 房源图片
const houseImages = ref([])

// 位置信息 - 根据HouseRequest类重新设计
const locationInfo = ref({
  houseLocation: '',        // 房源位置
  latitude: null,           // 纬度
  longitude: null,          // 经度
  subwayInfo: '',          // 地铁信息
  nearbyFacilities: []
})

// 地图对象
let map = null
let marker = null
let geocoder = null

// 审核相关
const reviewId = ref('')
const reviewProgress = ref(0)
const verifyStatus = ref(0) // 0=待审核，1=通过，2=驳回，3=已取消
const rejectReason = ref('') // 拒绝原因
const isCheckingStatus = ref(false) // 是否正在检查状态
const autoCheckTimer = ref(null) // 自动检查定时器
const publishing = ref(false) // 是否正在发布房源
const debugging = ref(false) // 是否正在调试
const developerMode = ref(false) // 开发者模式，跳过认证检查

// 导航相关功能现在由 UserLayout 组件处理

// 上一步
const prevStep = () => {
  if (currentStep.value === 5) {
    // 从审核状态返回
    currentStep.value = 4
  } else {
    currentStep.value--
  }
}

// 下一步
const nextStep = async () => {
  if (currentStep.value === 0) {
    // 检查是否同意协议
    if (!agreementAccepted.value) {
      ElMessage.warning('请先阅读并同意房源发布协议')
      return
    }
    // 验证房产证信息表单
    certificateFormRef.value.validate(async (valid) => {
      if (valid) {
        // 额外验证房产证图片
        if (certificateImages.value.length === 0) {
          ElMessage.warning('请上传房产证图片')
        } else {
          try {
            await submitHouse()
            // submitHouse() 函数内部已经设置了 currentStep.value = 1
            // 所以这里不需要再 currentStep.value++
          } catch (error) {
            console.error('提交房源失败:', error)
            ElMessage.error('提交失败，请重试')
          }
        }
      } else {
        ElMessage.warning('请填写完整的房产证信息')
      }
    })
  } else if (currentStep.value === 1) {
    // 检查审核状态
    if (verifyStatus.value === 1) {
      // 审核通过，可以进入下一步
      currentStep.value++
    } else if (verifyStatus.value === 0) {
      ElMessage.warning('请等待审核完成，您可以点击"查询审核状态"获取最新状态')
    } else if (verifyStatus.value === 2) {
      ElMessage.error('审核未通过，请查看驳回原因后重新提交')
    } else if (verifyStatus.value === 3) {
      ElMessage.warning('审核已取消，请重新提交申请')
    } else {
      ElMessage.warning('请先查询审核状态')
    }
  } else if (currentStep.value === 2) {
    // 验证房源信息表单
    try {
      await houseInfoFormRef.value.validate()
      currentStep.value++
    } catch (error) {
      ElMessage.error('请完善房源信息')
    }
  } else if (currentStep.value === 3) {
    // 验证位置信息
    if (!selectedPosition.value) {
      ElMessage.warning('请在地图上选择房源位置')
      return
    }
    if (!locationInfo.value.houseLocation.trim()) {
      ElMessage.warning('请填写房源位置描述')
      return
    }
    // 位置信息是最后一步，不需要再进入下一步
    ElMessage.success('位置信息填写完成，请点击"确认发布房源"按钮完成发布')
  }
}

// 根据值获取标签
const getLabelByValue = (value, options) => {
  const option = options.find(item => item.value === value)
  return option ? option.label : ''
}

// 显示协议
const showAgreement = () => {
  ElMessageBox.alert(`
    <h3 style="text-align: center; margin-bottom: 20px;">房源发布服务协议</h3>
    <p style="text-align: right; margin-bottom: 30px;">版本号：V1.0.0</p>

    <p>欢迎您使用本平台的房源发布服务。在发布房源前，请您仔细仔细阅读以下协议条款。您点击"同意"即表示您已阅读、理解并同意本协议的全部内容。</p>

    <h4>一、定义</h4>
    <p>1.1 "平台"：指本房源信息发布平台（HousingHub）。</p>
    <p>1.2 "发布者"：指通过本平台发布房源信息的用户，即您。</p>
    <p>1.3 "房源信息"：指发布者通过平台发布的与房屋租赁相关的所有信息，包括但不限于房屋基本信息、图片、价格等。</p>

    <h4>二、发布者声明与保证</h4>
    <p>2.1 发布者保证其为所发布房源的合法权利人或已获得合法权利人的有效授权，有权发布该房源信息并进行出租。</p>
    <p>2.2 发布者保证所发布的房源信息真实、准确、完整，不存在任何虚假、误导性陈述或重大遗漏。</p>
    <p>2.3 发布者保证所发布的房源符合国家及地方相关法律法规的要求，不存在违法违规情形。</p>
    <p>2.4 发布者保证所提供的房产证等证明文件真实有效，且与所发布房源信息一致。</p>

    <h4>三、房源信息规范</h4>
    <p>3.1 房源信息应包括但不限于以下内容：房屋地址、面积、户型、朝向、租金、配套设施、房屋照片等。</p>
    <p>3.2 禁止发布以下类型的信息：</p>
    <p>（1）违反国家法律法规的；</p>
    <p>（2）涉及色情、暴力、赌博等违法或不良信息的；</p>
    <p>（3）虚假、欺诈性信息；</p>
    <p>（4）侵犯他人知识产权或其他合法权益的；</p>
    <p>（5）其他平台认为不适宜发布的信息。</p>

    <h4>四、审核与管理</h4>
    <p>4.1 发布者提交房源信息后，平台将进行审核，审核通过后方可发布。</p>
    <p>4.2 平台有权对已发布的房源信息进行抽查，如发现不符合本协议或相关规定的，有权进行修改、删除或下架处理。</p>
    <p>4.3 房源信息审核周期一般为1-3个工作日，具体以实际审核时间为准。</p>

    <h4>五、知识产权</h4>
    <p>5.1 发布者对其发布的房源信息拥有合法权利，但授予平台免费、非独家的使用权，平台可在本平台范围内展示该信息。</p>
    <p>5.2 平台的所有知识产权归平台所有，发布者不得擅自使用。</p>

    <h4>六、法律责任</h4>
    <p>6.1 如发布者违反本协议约定，平台有权采取警告、限制功能、封号等措施，并保留追究其法律责任的权利。</p>
    <p>6.2 因发布者发布的房源信息引起的任何纠纷或法律责任，由发布者自行承担，如给平台造成损失的，应予以赔偿。</p>

    <h4>七、其他</h4>
    <p>7.1 本协议的订立、效力、解释、履行及争议解决均适用中华人民共和国法律。</p>
    <p>7.2 因本协议引起的或与本协议有关的任何争议，双方应友好协商解决；协商不成的，任何一方均有权向平台所在地有管辖权的人民法院提起诉讼。</p>
    <p>7.3 平台有权根据业务发展需要修改本协议，修改后的协议将在平台公示，公示后继续使用平台服务即视为同意修改后的协议。</p>
  `, '房源发布协议', {
    confirmButtonText: '确定',
    dangerouslyUseHTMLString: true,
    width: '700px'
  })
}

// 处理房产证图片上传
const handleCertificateImageChange = (file, fileList) => {
  certificateImages.value = fileList
}

// 处理房产证图片移除
const handleCertificateImageRemove = (file, fileList) => {
  certificateImages.value = fileList
}

// 处理房源图片上传
const handleImageChange = (file, fileList) => {
  houseImages.value = fileList
}

// 处理房源图片移除
const handleImageRemove = (file, fileList) => {
  houseImages.value = fileList
}

// 选择封面图片
const selectCoverImage = (index) => {
  coverImageIndex.value = index
}

// 初始化地图
const initMap = () => {
  nextTick(() => {
    // 检查是否已加载高德地图API
    if (window.AMap) {
      createMap()
    } else {
      // 动态加载高德地图API
      loadAMapScript(() => {
        createMap()
      })
    }
  })
}

// 加载高德地图API
const loadAMapScript = (callback) => {
  const script = document.createElement('script')
  script.src = 'https://webapi.amap.com/maps?v=2.0&key=7e30aec5d3498d19e07ba30d2a409dab'
  script.onload = () => {
    console.log('高德地图API加载成功')
    callback()
  }
  script.onerror = () => {
    ElMessage.error('高德地图API加载失败，请检查网络连接')
    console.error('高德地图API加载失败')
  }
  document.head.appendChild(script)
}

// 创建地图
const createMap = () => {
  try {
    map = new window.AMap.Map('map-container', {
      resizeEnable: true,
      zoom: 12,
      center: [116.397428, 39.90923] // 默认北京天安门
    })

    // 添加标记
    marker = new window.AMap.Marker({
      map: map,
      draggable: true,
      cursor: 'move'
    })

    // 添加点击事件 - 点击地图获取经纬度
    map.on('click', function(e) {
      const lnglat = e.lnglat
      const longitude = lnglat.getLng()
      const latitude = lnglat.getLat()

      // 设置标记位置
      marker.setPosition(lnglat)

      // 保存选择的位置
      selectedPosition.value = {
        longitude: longitude,
        latitude: latitude,
        address: `经度: ${longitude.toFixed(6)}, 纬度: ${latitude.toFixed(6)}`
      }

      ElMessage.success('位置选择成功')
      console.log('选择的位置:', selectedPosition.value)
    })

    // 添加标记拖拽结束事件
    marker.on('dragend', function(e) {
      const lnglat = e.lnglat
      const longitude = lnglat.getLng()
      const latitude = lnglat.getLat()

      // 保存拖拽后的位置
      selectedPosition.value = {
        longitude: longitude,
        latitude: latitude,
        address: `经度: ${longitude.toFixed(6)}, 纬度: ${latitude.toFixed(6)}`
      }

      ElMessage.success('位置更新成功')
      console.log('拖拽后的位置:', selectedPosition.value)
    })

    ElMessage.success('地图加载成功，请点击地图选择位置')
  } catch (error) {
    console.error('地图创建失败:', error)
    ElMessage.error('地图创建失败，请刷新页面重试')
  }
}

// 清除位置选择
const clearSelection = () => {
  selectedPosition.value = null
  locationInfo.value.houseLocation = ''
  locationInfo.value.subwayInfo = ''
  if (marker && map) {
    marker.setMap(null)
  }
  ElMessage.success('已清除位置选择')
}

// 获取当前位置
const getCurrentLocation = () => {
  if (!navigator.geolocation) {
    ElMessage.error('您的浏览器不支持地理位置定位')
    return
  }

  locating.value = true

  navigator.geolocation.getCurrentPosition(
    (position) => {
      const longitude = position.coords.longitude
      const latitude = position.coords.latitude

      // 更新地图中心和标记位置
      if (map && marker) {
        const lnglat = new window.AMap.LngLat(longitude, latitude)
        map.setCenter(lnglat)
        map.setZoom(16) // 放大到更详细的级别
        marker.setPosition(lnglat)

        // 保存当前位置
        selectedPosition.value = {
          longitude: longitude,
          latitude: latitude,
          address: `经度: ${longitude.toFixed(6)}, 纬度: ${latitude.toFixed(6)}`
        }

        ElMessage.success('定位成功！已自动选择当前位置')
        console.log('当前位置:', selectedPosition.value)
      } else {
        ElMessage.error('地图未初始化，请稍后重试')
      }

      locating.value = false
    },
    (error) => {
      locating.value = false
      let errorMessage = '定位失败'

      switch(error.code) {
        case error.PERMISSION_DENIED:
          errorMessage = '用户拒绝了地理位置请求'
          break
        case error.POSITION_UNAVAILABLE:
          errorMessage = '位置信息不可用'
          break
        case error.TIMEOUT:
          errorMessage = '定位请求超时'
          break
        default:
          errorMessage = '定位时发生未知错误'
          break
      }

      ElMessage.error(errorMessage)
      console.error('定位错误:', error)
    },
    {
      enableHighAccuracy: true, // 启用高精度定位
      timeout: 10000, // 10秒超时
      maximumAge: 60000 // 缓存1分钟
    }
  )
}





// 处理提交逻辑
  const handleSubmit = async () => {
    try {
      await submitHouse();
      nextStep();
    } catch (error) {
      console.error('submitHouse执行失败，不执行nextStep:', error);
    }
  }

// 提交房源信息审核
  const submitHouse = async () => {
    return new Promise(async (resolve, reject) => {
      if (!agreementAccepted.value) {
        ElMessage.warning('请先同意房源发布协议')
        submitting.value = false
        return Promise.reject(new Error('请先同意房源发布协议'))
      }

      submitting.value = true

      // 准备提交数据
      let propertyVerificationRequest = null;

      //从localStorage获取用户信息
      console.log('检查localStorage中的userInfo');
      const userInfoStr = localStorage.getItem('userInfo');
      console.log('userInfoStr:', userInfoStr);
      if (!userInfoStr) {
        ElMessage.error('未找到用户信息，请先登录');
        submitting.value = false;
        reject(new Error('未找到用户信息'));
        return;
      }

      try {
        const userInfo = JSON.parse(userInfoStr);
        const userId = userInfo.id; // 获取用户ID

        if (!userId) {
          ElMessage.error('用户信息不完整，请重新登录');
          submitting.value = false;
          reject(new Error('用户信息不完整'));
          return;
        }

        // 检查图片是否存在
        if (!certificateImages.value || certificateImages.value.length === 0) {
          ElMessage.error('请先上传房产证图片');
          submitting.value = false;
          return;
        }

        // 获取第一张房产证图片
        const firstImage = certificateImages.value[0];
        if (!firstImage.raw) {
          ElMessage.error('图片格式不正确，请重新上传');
          submitting.value = false;
          return;
        }

        ElMessage.info('正在提交审核，请稍候...');

        // 上传图片到OSS
        let imageUrl = '';
        try {
          imageUrl = await uploadImageToOSS(firstImage.raw);
          // 不显示图片上传成功的提示，等待最终提交结果
        } catch (uploadError) {
          console.error('图片上传失败:', uploadError);
          ElMessage.error('图片上传失败，请重试');
          submitting.value = false;
          return;
        }

        propertyVerificationRequest = {
          userId: userId,
          propertyNo: certificateInfo.value.certificateNumber,
          propertyPicPath: imageUrl,
          propertyAddr: certificateInfo.value.propertyAddress,
          verifyStatus: 0,
          isDelete: false
        };

        console.log('准备提交房产认证数据:', propertyVerificationRequest);

        // 验证必需字段
        if (!propertyVerificationRequest.userId) {
          ElMessage.error('用户ID不能为空');
          submitting.value = false;
          reject(new Error('用户ID不能为空'));
          return;
        }

        if (!propertyVerificationRequest.propertyNo) {
          ElMessage.error('房产证编号不能为空');
          submitting.value = false;
          reject(new Error('房产证编号不能为空'));
          return;
        }

        if (!propertyVerificationRequest.propertyPicPath) {
          ElMessage.error('房产证图片不能为空');
          submitting.value = false;
          reject(new Error('房产证图片不能为空'));
          return;
        }

        if (!propertyVerificationRequest.propertyAddr) {
          ElMessage.error('房产地址不能为空');
          submitting.value = false;
          reject(new Error('房产地址不能为空'));
          return;
        }
      } catch (error) {
        ElMessage.error('解析用户信息失败');
        console.error('解析用户信息失败:', error);
        submitting.value = false;
        reject(new Error('解析用户信息失败'));
        return;
      }

      // 调用后端API提交房源验证
      // 检查网络状态
      if (!navigator.onLine) {
        console.error('网络连接已断开');
        ElMessage.error('网络连接已断开，请检查网络后重试');
        submitting.value = false;
        reject(new Error('网络连接已断开'));
        return;
      }

      submitPropertyVerification(propertyVerificationRequest)
          .then(response => {
            console.log('房产认证提交成功，响应:', response)
            submitting.value = false

            // 检查响应状态码
            if (response.data.code === '200') {
              // 清除所有可能的表单验证状态
              if (certificateFormRef.value) {
                certificateFormRef.value.clearValidate()
              }
              if (houseInfoFormRef.value) {
                houseInfoFormRef.value.clearValidate()
              }
              // 清空所有消息提示
              ElMessage.closeAll()
              ElMessage.success('房源已提交审核，正在等待审核结果')
              // 更新步骤为"待审核"
              currentStep.value = 1
              // 使用后端返回的房产验证ID
              if (response.data.data && response.data.data.propertyVerifyId) {
                reviewId.value = response.data.data.propertyVerifyId
              } else {
                // 如果后端没有返回ID，生成临时ID
                reviewId.value = 'TEMP-' + Date.now()
              }
              // 初始化审核状态
              verifyStatus.value = 0 // 待审核
              reviewProgress.value = 30
              resolve();
            } else {
              // 后端返回了错误状态码
              ElMessage.error(response.data.message || '提交失败，请检查输入信息');
              reject(new Error(response.data.message || '提交失败'));
            }
          })
          .catch(error => {
            console.error('房产认证提交失败:', error)
            submitting.value = false

            // 清空所有消息提示
            ElMessage.closeAll()

            // 详细的错误处理
            if (error.response) {
              const status = error.response.status;
              const responseData = error.response.data;

              if (status === 400) {
                // 参数验证错误
                if (responseData && responseData.message) {
                  // 如果后端返回了具体的验证错误信息
                  ElMessage.error(`数据验证失败: ${responseData.message}`);
                } else {
                  // 通用的参数验证错误提示
                  ElMessage.error('提交的数据格式不正确，请检查房产证编号和地址格式');
                }
              } else if (status === 500) {
                ElMessage.error('系统内部错误，请联系管理员');
              } else if (status === 401) {
                ElMessage.error('未授权访问，请重新登录');
              } else if (status === 403) {
                ElMessage.error('权限不足，请联系管理员');
              } else {
                ElMessage.error(`提交失败: ${status} ${error.response.statusText}`);
              }
            } else if (error.message.includes('ECONNREFUSED')) {
              ElMessage.error('无法连接到服务器，请检查网络连接或联系管理员')
            } else if (error.message.includes('timeout')) {
              ElMessage.error('请求超时，请稍后重试')
            } else {
              ElMessage.error('网络错误，请检查网络连接或联系管理员');
            }

            reject(error);
            // 不更新步骤和审核状态
          })
    })
  }

// 查询审核状态
const checkReviewStatus = async (showMessage = true) => {
  // 检查是否有房产证编号
  if (!certificateInfo.value.certificateNumber) {
    if (showMessage) {
      ElMessage.warning('无法查询审核状态，请确保已输入房产证编号')
    }
    return
  }

  isCheckingStatus.value = true

  if (showMessage) {
    ElMessage.info('正在查询审核状态...')
  }

  try {
    const response = await getPropertyVerifyStatus(certificateInfo.value.certificateNumber)

    if (response.data.code === '200') {
      const statusValue = response.data.data

      // 更新状态变量
      verifyStatus.value = statusValue

      switch (statusValue) {
        case 0:
          // 待审核
          if (showMessage) {
            ElMessage.info('审核状态：审核中，预计1-15个工作日完成审核，请耐心等待')
          }
          reviewProgress.value = 50 // 更新进度条
          // 如果是待审核状态，启动自动检查
          startAutoStatusCheck()
          break

        case 1:
          // 审核通过
          if (showMessage) {
            ElMessage.success('恭喜！您的房产认证已通过审核，可以继续下一步操作')
          }
          reviewProgress.value = 100 // 完成进度
          // 停止自动检查
          stopAutoStatusCheck()
          break

        case 2:
          // 审核被驳回
          if (showMessage) {
            ElMessage.error('很抱歉，您的房产认证审核未通过')
          }
          reviewProgress.value = 0 // 重置进度
          // 自动获取拒绝原因（静默获取，不显示弹窗）
          await fetchRejectReasonSilently()
          // 停止自动检查
          stopAutoStatusCheck()
          break

        case 3:
          // 已取消
          if (showMessage) {
            ElMessage.info('审核已取消，您可以重新提交申请')
          }
          reviewProgress.value = 0 // 重置进度
          // 停止自动检查
          stopAutoStatusCheck()
          break

        default:
          if (showMessage) {
            ElMessage.warning('未知的审核状态')
          }
      }
    } else {
      if (showMessage) {
        ElMessage.error(response.data.message || '查询审核状态失败')
      }
    }
  } catch (error) {
    console.error('查询审核状态失败:', error)

    if (showMessage) {
      if (error.response) {
        const status = error.response.status
        const responseData = error.response.data

        if (status === 404 || (responseData && responseData.message && responseData.message.includes('不存在'))) {
          ElMessage.error('未找到该房产证编号的认证记录，请确认编号是否正确')
        } else {
          ElMessage.error('查询审核状态失败，请稍后重试')
        }
      } else {
        ElMessage.error('网络错误，请检查网络连接')
      }
    }
  } finally {
    isCheckingStatus.value = false
  }
}

// 启动自动状态检查
const startAutoStatusCheck = () => {
  // 清除之前的定时器
  stopAutoStatusCheck()

  // 每5小时检查一次状态（仅在待审核状态下）
  autoCheckTimer.value = setInterval(async () => {
    if (verifyStatus.value === 0 && certificateInfo.value.certificateNumber) {
      await checkReviewStatus(false) // 静默检查，不显示消息
    } else {
      // 如果状态不是待审核，停止自动检查
      stopAutoStatusCheck()
    }
  }, 5 * 60 * 60 * 1000) // 5小时检查一次
}

// 停止自动状态检查
const stopAutoStatusCheck = () => {
  if (autoCheckTimer.value) {
    clearInterval(autoCheckTimer.value)
    autoCheckTimer.value = null
  }
}

// 自动获取最新审核状态（进入页面时调用）
const autoCheckReviewStatus = async () => {
  // 检查是否有房产证编号
  if (!certificateInfo.value.certificateNumber) {
    return
  }

  try {
    const response = await getPropertyVerifyStatus(certificateInfo.value.certificateNumber)

    if (response.data.code === '200') {
      const statusValue = response.data.data

      // 更新状态变量
      verifyStatus.value = statusValue

      switch (statusValue) {
        case 0:
          // 待审核
          reviewProgress.value = 50
          // 启动自动检查
          startAutoStatusCheck()
          break

        case 1:
          // 审核通过
          reviewProgress.value = 100
          break

        case 2:
          // 审核被驳回
          reviewProgress.value = 0
          // 自动获取拒绝原因
          await fetchRejectReasonSilently()
          break

        case 3:
          // 已取消
          reviewProgress.value = 0
          break
      }
    }
  } catch (error) {
    console.error('自动获取审核状态失败:', error)
    // 静默失败，不显示错误信息，避免影响用户体验
  }
}

// 静默获取拒绝原因（不显示弹窗，只更新本地状态）
const fetchRejectReasonSilently = async () => {
  if (!certificateInfo.value.certificateNumber) {
    return
  }

  try {
    const response = await getPropertyVerifyRefuseReason(certificateInfo.value.certificateNumber)

    if (response.data.code === '200' && response.data.data) {
      rejectReason.value = response.data.data
    }
  } catch (error) {
    console.error('静默获取拒绝原因失败:', error)
    // 静默失败，不显示错误信息
  }
}

// 查询拒绝原因
const queryRejectReason = async () => {
  // 检查是否有房产证编号
  if (!certificateInfo.value.certificateNumber) {
    ElMessage.warning('无法查询拒绝原因，请确保已输入房产证编号')
    return
  }

  try {
    ElMessage.info('正在查询拒绝原因...')

    const response = await getPropertyVerifyRefuseReason(certificateInfo.value.certificateNumber)

    if (response.data.code === '200') {
      const refuseReason = response.data.data

      if (refuseReason && refuseReason.trim()) {
        // 显示具体的拒绝原因
        ElMessageBox.alert(
          refuseReason,
          '审核未通过原因',
          {
            confirmButtonText: '我知道了',
            type: 'error',
            dangerouslyUseHTMLString: false // 确保安全，不解析HTML
          }
        )
        // 更新本地的拒绝原因
        rejectReason.value = refuseReason
      } else {
        // 如果没有具体原因，显示通用提示
        ElMessageBox.alert(
          '您的房产认证审核未通过，但未提供具体原因。\n' +
          '可能的原因包括：\n' +
          '1. 房产证编号格式不正确\n' +
          '2. 房产证图片不清晰或不完整\n' +
          '3. 房产地址信息不准确\n' +
          '4. 其他资料问题\n\n' +
          '请检查您的资料后重新提交申请。',
          '审核未通过原因',
          {
            confirmButtonText: '我知道了',
            type: 'error'
          }
        )
      }
    } else {
      ElMessage.error(response.data.message || '查询拒绝原因失败')
    }
  } catch (error) {
    console.error('查询拒绝原因失败:', error)

    if (error.response) {
      const status = error.response.status
      const responseData = error.response.data

      if (status === 404 || (responseData && responseData.message && responseData.message.includes('不存在'))) {
        ElMessage.error('未找到该房产证编号的认证记录')
      } else {
        ElMessage.error('查询拒绝原因失败，请稍后重试')
      }
    } else {
      ElMessage.error('网络错误，请检查网络连接')
    }
  }
}

// 取消审核
const cancelReview = async () => {
  // 检查审核状态，只有待审核状态才能取消
  if (verifyStatus.value !== 0) {
    if (verifyStatus.value === 1) {
      ElMessage.warning('审核已通过，无法取消')
    } else if (verifyStatus.value === 2) {
      ElMessage.warning('审核已被驳回，无法取消')
    } else if (verifyStatus.value === 3) {
      ElMessage.warning('审核已取消，无法重复取消')
    } else {
      ElMessage.warning('当前状态无法取消审核')
    }
    return
  }

  // 检查是否有房产证编号
  if (!certificateInfo.value.certificateNumber) {
    ElMessage.warning('无法取消审核，请确保已输入房产证编号')
    return
  }

  try {
    await ElMessageBox.confirm(
      '确定要取消审核吗？取消后需要重新提交。',
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 用户确认取消，调用后端API
    ElMessage.info('正在取消审核...')

    const response = await cancelPropertyVerify(certificateInfo.value.certificateNumber)

    if (response.data.code === '200') {
      ElMessage.success('审核已取消')
      // 更新状态为已取消
      verifyStatus.value = 3
      reviewProgress.value = 0
      rejectReason.value = '' // 清空拒绝原因
      // 重置到第一步
      currentStep.value = 0
    } else {
      ElMessage.error(response.data.message || '取消审核失败')
    }
  } catch (error) {
    if (error === 'cancel') {
      // 用户取消操作，不显示错误信息
      return
    }

    console.error('取消审核失败:', error)

    if (error.response) {
      const status = error.response.status
      const responseData = error.response.data

      if (status === 404 || (responseData && responseData.message && responseData.message.includes('不存在'))) {
        ElMessage.error('未找到该房产证编号的认证记录')
      } else {
        ElMessage.error('取消审核失败，请稍后重试')
      }
    } else {
      ElMessage.error('网络错误，请检查网络连接')
    }
  }
}

// 监听步骤变化
watch(currentStep, (newStep) => {
  if (newStep === 1) {
    // 进入审核状态页面时，自动获取最新审核状态
    autoCheckReviewStatus()
  } else if (newStep === 3) {
    // 进入位置信息页面时初始化地图
    initMap()
  }
}, { immediate: false })

// 重置页面状态的函数
const resetPageState = () => {
  currentStep.value = 0
  verifyStatus.value = null
  reviewProgress.value = 0
  certificateInfo.value.certificateNumber = ''
  certificateInfo.value.certificateAddress = ''
  certificateInfo.value.detailAddress = ''
  certificateImages.value = []
  houseImages.value = []
  selectedPosition.value = null
  agreementAccepted.value = false

  // 清理localStorage中的相关数据
  localStorage.removeItem('savedCertificateNumber')
}

// 监听用户信息变化，当用户切换时重置状态
watch(() => {
  const userInfoStr = localStorage.getItem('userInfo')
  return userInfoStr ? JSON.parse(userInfoStr).id : null
}, (newUserId, oldUserId) => {
  if (oldUserId !== null && newUserId !== oldUserId) {
    console.log('检测到用户切换，重置页面状态')
    resetPageState()
  }
}, { immediate: false })

// 组件挂载后的初始化
onMounted(async () => {
  // 检查登录状态
  const loginStatus = checkLoginStatus()
  console.log('页面加载时的登录状态:', loginStatus)

  if (!loginStatus.isUserLoggedIn && !loginStatus.isAdminLoggedIn) {
    ElMessage.warning('请先登录后再发布房源')
    router.push('/login')
    return
  }

  // 重置步骤到初始状态
  currentStep.value = 0
  verifyStatus.value = null
  reviewProgress.value = 0

  // 获取当前用户信息
  const userInfoStr = localStorage.getItem('userInfo')
  if (!userInfoStr) {
    ElMessage.warning('用户信息不完整，请重新登录')
    router.push('/login')
    return
  }

  const userInfo = JSON.parse(userInfoStr)
  const userId = userInfo.id

  try {
    // 检查当前用户是否有房产认证记录
    console.log('正在检查用户ID:', userId, '的房产认证记录')
    const response = await getPropertyVerificationByUserId(userId)

    if (response.data.code === '200' && response.data.data && response.data.data.length > 0) {
      // 找到最新的认证记录
      const latestVerification = response.data.data[0] // 假设返回的数据按时间排序
      console.log('找到认证记录:', latestVerification)

      if (latestVerification && latestVerification.propertyNo) {
        // 检查认证状态，只有在审核中或已通过的情况下才跳转到状态页面
        // 不自动填充房产证编号，让用户自己决定是查看现有认证还是提交新认证

        // 先检查审核状态（不填充编号）
        const tempCertificateNumber = latestVerification.propertyNo
        try {
          const statusResponse = await getPropertyVerifyStatus(tempCertificateNumber)
          if (statusResponse.data.code === '200') {
            const statusValue = statusResponse.data.data

            // 只有在待审核(0)状态时才自动跳转到审核状态页面
            if (statusValue === 0) {
              // 填充房产证编号并跳转到审核状态页面
              certificateInfo.value.certificateNumber = tempCertificateNumber
              verifyStatus.value = statusValue
              reviewId.value = latestVerification.propertyVerifyId // 使用房产验证ID
              currentStep.value = 1
              console.log('用户有待审核的认证，跳转到审核状态页面，验证ID:', reviewId.value)

              // 保存房产证编号到localStorage
              localStorage.setItem('savedCertificateNumber', tempCertificateNumber)
            } else {
              // 如果是已通过(1)、已驳回(2)或已取消(3)，保持在第一步让用户重新提交或查看状态
              console.log('用户的认证已结束，保持在第一步让用户重新提交')
            }
          }
        } catch (statusError) {
          console.log('检查认证状态失败，保持在第一步')
        }
      }
    } else {
      // 没有认证记录，清理可能存在的旧数据
      console.log('用户没有认证记录，保持在第一步')
      localStorage.removeItem('savedCertificateNumber')
      certificateInfo.value.certificateNumber = ''
    }
  } catch (error) {
    console.error('获取用户认证信息失败:', error)
    // 发生错误时，保持在第一步
    currentStep.value = 0
  }

  // 如果当前在位置信息页面，初始化地图
  if (currentStep.value === 3) {
    initMap()
  }
})

// 确认发布房源
const confirmPublish = async () => {
  // 验证房源信息表单
  if (!houseInfoFormRef.value) {
    ElMessage.error('表单未初始化')
    return
  }

  try {
    await houseInfoFormRef.value.validate()
  } catch (error) {
    ElMessage.error('请完善房源信息')
    currentStep.value = 2 // 跳转到房源信息页面
    return
  }

  // 验证位置信息
  if (!locationInfo.value.houseLocation.trim()) {
    ElMessage.error('请填写房源位置描述')
    currentStep.value = 3 // 跳转到位置信息页面
    return
  }

  if (!selectedPosition.value) {
    ElMessage.error('请在地图上选择房源位置')
    currentStep.value = 3 // 跳转到位置信息页面
    return
  }

  // 更新位置信息
  locationInfo.value.latitude = selectedPosition.value.latitude
  locationInfo.value.longitude = selectedPosition.value.longitude

  // 调用发布函数
  await publishFinalHouse()
}

// 最终发布房源 - 在位置信息确定后调用
const publishFinalHouse = async () => {
  publishing.value = true

  try {
    // 验证必需的数据
    if (!locationInfo.value.latitude || !locationInfo.value.longitude) {
      ElMessage.error('请先在地图上选择房源位置')
      publishing.value = false
      return
    }

    // 获取用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (!userInfoStr) {
      ElMessage.error('未找到用户信息，请先登录')
      publishing.value = false
      return
    }

    const userInfo = JSON.parse(userInfoStr)
    const userId = userInfo.id

    // 获取已通过审核的房产认证ID
    // 这里需要根据房产证编号查询propertyVerifyId
    let propertyVerifyId = null
    try {
      const verificationResponse = await getPropertyVerificationByUserId(userId)
      console.log('获取房产认证响应:', verificationResponse)

      if (verificationResponse.data.code === '200' && verificationResponse.data.data) {
        console.log('房产认证数据:', verificationResponse.data.data)
        console.log('当前房产证编号:', certificateInfo.value.certificateNumber)

        // 找到对应房产证编号的认证记录
        const verification = verificationResponse.data.data.find(v => {
          console.log('检查认证记录:', v)
          return v.propertyNo === certificateInfo.value.certificateNumber && v.verifyStatus === 1
        })

        if (verification) {
          // 使用正确的字段名 propertyVerifyId
          propertyVerifyId = verification.propertyVerifyId
          console.log('找到匹配的认证记录，ID:', propertyVerifyId)
        } else {
          console.log('未找到匹配的认证记录')
          // 显示更详细的错误信息
          const allVerifications = verificationResponse.data.data
          const currentCertNumber = certificateInfo.value.certificateNumber

          if (allVerifications.length === 0) {
            ElMessage.error('您还没有提交过房产认证，请先完成房产认证')
          } else {
            const matchingNumber = allVerifications.find(v => v.propertyNo === currentCertNumber)
            if (!matchingNumber) {
              ElMessage.error(`未找到房产证编号为 ${currentCertNumber} 的认证记录`)
            } else if (matchingNumber.verifyStatus !== 1) {
              const statusText = matchingNumber.verifyStatus === 0 ? '待审核' :
                               matchingNumber.verifyStatus === 2 ? '已驳回' : '已取消'
              ElMessage.error(`房产证编号 ${currentCertNumber} 的认证状态为：${statusText}，只有审核通过的认证才能发布房源`)
            }
          }
        }
      }
    } catch (error) {
      console.error('获取房产认证信息失败:', error)
      ElMessage.error('获取房产认证信息失败，请稍后重试')
    }

    if (!propertyVerifyId) {
      publishing.value = false
      return
    }

    // 构建HouseRequest数据
    const houseRequest = {
      userId: userId,
      houseTitle: houseInfo.value.houseTitle,
      propertyVerifyId: propertyVerifyId,
      houseSummary: houseInfo.value.houseSummary,
      complementaryFacilities: houseInfo.value.complementaryFacilities,
      houseLocation: locationInfo.value.houseLocation,
      layout: houseInfo.value.layout,
      floor: houseInfo.value.floor,
      area: houseInfo.value.area,
      orientation: houseInfo.value.orientation,
      phone: houseInfo.value.phone,
      rent: houseInfo.value.rent,
      paymentType: houseInfo.value.paymentType,
      rentType: houseInfo.value.rentType,
      longitude: locationInfo.value.longitude,
      latitude: locationInfo.value.latitude,
      subwayInfo: locationInfo.value.subwayInfo || '',
      depositType: houseInfo.value.depositType
    }

    console.log('准备发布房源数据:', houseRequest)

    // 调用发布房源API
    const response = await publishHouse(houseRequest)

    if (response.data.code === '200') {
      ElMessage.success('房源发布成功！')

      // 准备房源信息用于成功页面展示
      const houseInfoForSuccess = {
        houseTitle: houseInfo.value.houseTitle,
        layout: houseInfo.value.layout,
        area: houseInfo.value.area,
        rent: houseInfo.value.rent
      }

      // 跳转到发布成功页面
      router.push({
        path: '/house/publish-success',
        query: {
          houseInfo: encodeURIComponent(JSON.stringify(houseInfoForSuccess))
        }
      })
    } else {
      ElMessage.error(response.data.message || '房源发布失败')
    }

  } catch (error) {
    console.error('发布房源失败:', error)
    ElMessage.error('发布房源失败，请重试')
  } finally {
    publishing.value = false
  }
}

// 调试房产认证状态
const debugPropertyVerification = async () => {
  debugging.value = true

  try {
    // 获取用户信息
    const userInfoStr = localStorage.getItem('userInfo')
    if (!userInfoStr) {
      ElMessage.error('未找到用户信息，请先登录')
      debugging.value = false
      return
    }

    const userInfo = JSON.parse(userInfoStr)
    const userId = userInfo.id

    console.log('调试信息 - 用户ID:', userId)
    console.log('调试信息 - 当前房产证编号:', certificateInfo.value.certificateNumber)

    // 获取房产认证信息
    const verificationResponse = await getPropertyVerificationByUserId(userId)
    console.log('调试信息 - API响应:', verificationResponse)

    if (verificationResponse.data.code === '200') {
      const verifications = verificationResponse.data.data || []
      console.log('调试信息 - 认证记录数量:', verifications.length)

      let debugMessage = `用户ID: ${userId}\n当前房产证编号: ${certificateInfo.value.certificateNumber}\n\n`
      debugMessage += `共找到 ${verifications.length} 条房产认证记录:\n\n`

      verifications.forEach((v, index) => {
        const statusText = v.verifyStatus === 0 ? '待审核' :
                          v.verifyStatus === 1 ? '已通过' :
                          v.verifyStatus === 2 ? '已驳回' : '已取消'
        debugMessage += `记录 ${index + 1}:\n`
        debugMessage += `  - 认证ID: ${v.propertyVerifyId}\n`
        debugMessage += `  - 房产证编号: ${v.propertyNo}\n`
        debugMessage += `  - 认证状态: ${statusText} (${v.verifyStatus})\n`
        debugMessage += `  - 房产地址: ${v.propertyAddr}\n`
        debugMessage += `  - 申请时间: ${v.applyTime}\n`
        if (v.refuseReason) {
          debugMessage += `  - 拒绝原因: ${v.refuseReason}\n`
        }
        debugMessage += '\n'
      })

      // 检查匹配的认证记录
      const matchingVerification = verifications.find(v =>
        v.propertyNo === certificateInfo.value.certificateNumber
      )

      if (matchingVerification) {
        debugMessage += `匹配的认证记录:\n`
        debugMessage += `  - 认证ID: ${matchingVerification.propertyVerifyId}\n`
        debugMessage += `  - 状态: ${matchingVerification.verifyStatus === 1 ? '✅ 已通过' : '❌ 未通过'}\n`

        if (matchingVerification.verifyStatus === 1) {
          debugMessage += `\n✅ 该房产证可以用于发布房源！`
        } else {
          debugMessage += `\n❌ 该房产证不能用于发布房源，状态不是"已通过"`
        }
      } else {
        debugMessage += `❌ 未找到房产证编号为 "${certificateInfo.value.certificateNumber}" 的认证记录`
      }

      ElMessageBox.alert(debugMessage, '房产认证调试信息', {
        confirmButtonText: '确定',
        type: 'info'
      })
    } else {
      ElMessage.error('获取房产认证信息失败: ' + verificationResponse.data.message)
    }
  } catch (error) {
    console.error('调试失败:', error)
    ElMessage.error('调试失败: ' + error.message)
  } finally {
    debugging.value = false
  }
}

// 切换开发者模式
const toggleDeveloperMode = () => {
  developerMode.value = !developerMode.value
  if (developerMode.value) {
    ElMessage.warning('⚠️ 开发者模式已开启：将跳过房产认证检查，仅用于测试！')
  } else {
    ElMessage.info('开发者模式已关闭')
  }
}

// 监听步骤变化，在位置信息步骤初始化地图
watch(currentStep, (newStep) => {
  if (newStep === 3) {
    // 延迟初始化地图，确保DOM已渲染
    nextTick(() => {
      setTimeout(() => {
        initMap()
      }, 100)
    })
  }
})

// 页面卸载时清理
onUnmounted(() => {
  // 停止自动状态检查
  stopAutoStatusCheck()

  // 清理地图资源
  if (map) {
    map.destroy()
    map = null
  }
  if (marker) {
    marker = null
  }
  if (geocoder) {
    geocoder = null
  }
})
</script>

<style scoped>
.publish-house-content {
  width: 100%;
  height: 100%;
  background: linear-gradient(to bottom, #1a2980, #26d0ce);
  overflow: hidden;
}

/* 建筑物 */
.building {
  position: absolute;
  bottom: 0;
  background: rgba(30, 30, 50, 0.8);
  border-radius: 5px 5px 0 0;
  box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
}

.building-1 {
  left: 10%;
  width: 80px;
  height: 300px;
  animation: buildingGlow 4s infinite alternate;
}

.building-2 {
  left: 25%;
  width: 120px;
  height: 400px;
  animation: buildingGlow 5s infinite alternate-reverse;
}

.building-3 {
  left: 45%;
  width: 100px;
  height: 350px;
  animation: buildingGlow 6s infinite alternate;
}

.building-4 {
  left: 65%;
  width: 140px;
  height: 450px;
  animation: buildingGlow 4.5s infinite alternate-reverse;
}

.building-5 {
  left: 80%;
  width: 90px;
  height: 320px;
  animation: buildingGlow 5.5s infinite alternate;
}

@keyframes buildingGlow {
  0% {
    box-shadow: 0 -5px 15px rgba(0, 0, 0, 0.3);
  }
  100% {
    box-shadow: 0 -5px 25px rgba(100, 200, 255, 0.6);
  }
}

/* 云朵 */
.cloud {
  position: absolute;
  background: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
  filter: blur(2px);
}

.cloud-1 {
  top: 20%;
  left: 5%;
  width: 80px;
  height: 30px;
  animation: cloudMove 25s linear infinite;
}

.cloud-2 {
  top: 35%;
  left: 70%;
  width: 120px;
  height: 40px;
  animation: cloudMove 30s linear infinite;
}

.cloud-3 {
  top: 15%;
  left: 40%;
  width: 100px;
  height: 35px;
  animation: cloudMove 35s linear infinite;
}

@keyframes cloudMove {
  0% {
    transform: translateX(-100px);
  }
  100% {
    transform: translateX(calc(100vw + 100px));
  }
}

/* 太阳 */
.sun {
  position: absolute;
  top: 80px;
  right: 100px;
  width: 80px;
  height: 80px;
  background: radial-gradient(circle, #ffeb3b, #ffc107);
  border-radius: 50%;
  box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  animation: sunPulse 3s infinite alternate;
}

@keyframes sunPulse {
  0% {
    transform: scale(1);
    box-shadow: 0 0 40px #ff9800, 0 0 80px #ff5722;
  }
  100% {
    transform: scale(1.1);
    box-shadow: 0 0 60px #ff9800, 0 0 100px #ff5722;
  }
}

/* 光线 */
.light-ray {
  position: absolute;
  top: 120px;
  right: 140px;
  width: 400px;
  height: 200px;
  background: linear-gradient(to right, transparent, rgba(255, 235, 59, 0.2), transparent);
  transform-origin: left center;
  animation: rayRotate 10s infinite linear;
}

.ray-1 {
  transform: rotate(0deg);
  animation-delay: 0s;
}

.ray-2 {
  transform: rotate(60deg);
  animation-delay: 2s;
}

.ray-3 {
  transform: rotate(120deg);
  animation-delay: 4s;
}

@keyframes rayRotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

/* 浮动装饰元素 */
.floating-shape {
  position: absolute;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.1);
  animation: float 15s infinite linear;
}

.shape-1 {
  width: 300px;
  height: 300px;
  top: -100px;
  left: -100px;
  animation-duration: 20s;
  background: radial-gradient(circle, rgba(74, 144, 226, 0.2) 0%, transparent 70%);
}

.shape-2 {
  width: 200px;
  height: 200px;
  bottom: -80px;
  right: -80px;
  animation-duration: 25s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 107, 107, 0.2) 0%, transparent 70%);
}

.shape-3 {
  width: 150px;
  height: 150px;
  top: 30%;
  right: 20%;
  animation-duration: 15s;
  background: radial-gradient(circle, rgba(80, 227, 194, 0.2) 0%, transparent 70%);
}

.shape-4 {
  width: 100px;
  height: 100px;
  bottom: 20%;
  left: 20%;
  animation-duration: 18s;
  animation-direction: reverse;
  background: radial-gradient(circle, rgba(255, 209, 102, 0.2) 0%, transparent 70%);
}

.shape-5 {
  width: 250px;
  height: 250px;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  animation-duration: 22s;
  background: radial-gradient(circle, rgba(155, 89, 182, 0.2) 0%, transparent 70%);
}

.shape-6 {
  width: 180px;
  height: 180px;
  top: 70%;
  left: 10%;
  animation-duration: 28s;
  background: radial-gradient(circle, rgba(231, 76, 60, 0.2) 0%, transparent 70%);
}

@keyframes float {
  0% {
    transform: translate(0, 0) rotate(0deg);
  }
  25% {
    transform: translate(20px, 20px) rotate(90deg);
  }
  50% {
    transform: translate(0, 40px) rotate(180deg);
  }
  75% {
    transform: translate(-20px, 20px) rotate(270deg);
  }
  100% {
    transform: translate(0, 0) rotate(360deg);
  }
}

.publish-wrapper {
  width: 100%;
  padding: 20px;
}

/* 内容区域样式 - 现在由 UserLayout 组件处理背景装饰、导航栏和侧边栏 */

.publish-header {
  margin-bottom: 20px;
}

.publish-header h2 {
  color: #2c3e50;
  font-size: 28px;
  margin: 0 0 10px;
}

.publish-header p {
  color: #7f8c8d;
  font-size: 16px;
  margin: 0;
}

.publish-steps {
  margin-bottom: 30px;
}

.publish-content {
  flex: 1;
  background: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

.step-content {
  min-height: 400px;
}

.house-form,
.facility-form {
  max-width: 800px;
}

.map-section {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.map-header {
  margin-bottom: 20px;
}

.map-header h3 {
  margin: 0 0 10px;
  font-size: 20px;
  color: #2c3e50;
}

.map-header p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.map-search {
  margin-bottom: 20px;
  max-width: 500px;
}

.map-actions {
  margin-top: 10px;
  text-align: right;
}

.map-container {
  flex: 1;
  position: relative;
  border: 1px solid #ddd;
  border-radius: 8px;
  overflow: hidden;
}

.amap-container {
  width: 100%;
  height: 100%;
  min-height: 400px;
}

.position-info {
  position: absolute;
  top: 10px;
  left: 10px;
  background: rgba(255, 255, 255, 0.95);
  padding: 15px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 10;
  font-size: 13px;
  max-width: 300px;
  border: 1px solid #e0e0e0;
}

.position-info p {
  margin: 5px 0;
  line-height: 1.4;
}

.position-info strong {
  color: #2c3e50;
}

.address-details {
  margin-top: 10px;
  padding-top: 10px;
  border-top: 1px solid #eee;
}

.address-details p {
  margin: 3px 0;
  font-size: 12px;
  color: #666;
}

.map-instructions {
  margin-top: 10px;
  text-align: center;
  color: #7f8c8d;
  font-size: 14px;
}

.image-upload-section {
  padding: 20px 0;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 10px;
}

.cover-image-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.cover-image-item {
  width: 100px;
  height: 100px;
  border: 2px solid #ebeef5;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  position: relative;
}

.cover-image-item.active {
  border-color: #409eff;
}

.cover-image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.review-section h3,
.review-section h4 {
  color: #2c3e50;
  margin-bottom: 15px;
}

.review-images {
  margin: 30px 0;
}

.image-preview {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.preview-image {
  width: 150px;
  height: 150px;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  border: 1px solid #ebeef5;
}

.preview-image.cover {
  border-color: #409eff;
}

.preview-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-tag {
  position: absolute;
  top: 5px;
  right: 5px;
  background: #409eff;
  color: white;
  padding: 2px 5px;
  border-radius: 3px;
  font-size: 12px;
}

.review-facilities {
  margin: 30px 0;
}

.submit-section {
  margin-top: 30px;
  padding: 30px;
  background: rgba(74, 144, 226, 0.05);
  border-radius: 12px;
  border: 1px solid rgba(74, 144, 226, 0.2);
}

.submit-buttons {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 30px;
}

.submit-buttons .el-button {
  padding: 15px 40px;
  font-size: 16px;
  font-weight: 600;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(74, 144, 226, 0.3);
  transition: all 0.3s ease;
}

.submit-buttons .el-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(74, 144, 226, 0.4);
}

.form-navigation {
  display: flex;
  justify-content: space-between;
  padding: 20px 30px;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(10px);
  border-radius: 12px;
  margin-top: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
}

:deep(.el-progress__bar) {
  height: 8px !important;
  border-radius: 4px;
}

:deep(.el-progress__success-path) {
  background: linear-gradient(to right, #4A90E2, #5C6BC0) !important;
}

.review-actions {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

:deep(.review-actions .el-button) {
  padding: 10px 24px;
  font-size: 16px;
  border-radius: 8px;
}

:deep(.review-actions .el-button--text) {
  color: #f44336;
}



/* 重复样式已清理 */

@media (max-width: 992px) {
  .sidebar {
    width: 80px;
  }

  .app-title,
  .el-menu-item span,
  .el-sub-menu__title span {
    display: none;
  }

  .publish-content {
    padding: 15px;
  }

  .house-form .el-row {
    flex-direction: column;
    gap: 15px;
  }

  .house-form .el-col {
    width: 100%;
  }
}

/* 审核状态页面专属样式 */
.review-pending-section,
.review-success-section,
.review-rejected-section,
.review-cancelled-section {
  text-align: center;
  padding: 60px 20px;
  background: rgba(255, 255, 255, 0.5);
  border-radius: 12px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.05);
  margin: 40px auto;
  max-width: 800px;
}

.review-icon {
  margin-bottom: 30px;
  width: 120px;
  height: 120px;
  background: linear-gradient(135deg, #4A90E2 0%, #5C6BC0 100%);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-left: auto;
  margin-right: auto;
  box-shadow: 0 8px 20px rgba(74, 144, 226, 0.3);
}

.review-icon.success {
  background: linear-gradient(135deg, #67C23A 0%, #85CE61 100%);
  box-shadow: 0 8px 20px rgba(103, 194, 58, 0.3);
}

.review-icon.rejected {
  background: linear-gradient(135deg, #F56C6C 0%, #F78989 100%);
  box-shadow: 0 8px 20px rgba(245, 108, 108, 0.3);
}

.review-icon.cancelled {
  background: linear-gradient(135deg, #E6A23C 0%, #F7BA2A 100%);
  box-shadow: 0 8px 20px rgba(230, 162, 60, 0.3);
}

.review-icon .icon {
  font-size: 60px;
  color: white;
  animation: pulse 2s infinite alternate;
}

@keyframes pulse {
  0% { transform: scale(0.9); }
  100% { transform: scale(1.1); }
}

.review-pending-section h3,
.review-success-section h3,
.review-rejected-section h3,
.review-cancelled-section h3 {
  font-size: 26px;
  color: #2c3e50;
  margin: 0 0 20px;
  font-weight: 600;
}

.review-pending-section p,
.review-success-section p,
.review-rejected-section p,
.review-cancelled-section p {
  color: #666;
  font-size: 16px;
  margin: 0 0 30px;
  line-height: 1.6;
}

.review-id {
  color: #4A90E2;
  font-weight: 600;
  font-size: 18px;
  padding: 10px 0;
  border-top: 1px dashed #eee;
  border-bottom: 1px dashed #eee;
  margin: 20px auto 30px;
  max-width: 500px;
}

/* 拒绝原因框样式 */
.reject-reason-box {
  background: #fef0f0;
  border: 1px solid #fbc4c4;
  border-radius: 8px;
  padding: 20px;
  margin: 20px auto;
  max-width: 600px;
  text-align: left;
}

.reject-reason-box h4 {
  color: #f56c6c;
  font-size: 16px;
  font-weight: 600;
  margin: 0 0 10px 0;
}

.reject-reason-text {
  color: #666;
  font-size: 14px;
  line-height: 1.6;
  margin: 0;
  word-wrap: break-word;
}

.review-progress {
  max-width: 600px;
  margin: 30px auto;
  padding: 0 20px;
}

:deep(.el-progress__bar) {
  height: 8px !important;
  border-radius: 4px;
}

:deep(.el-progress__success-path) {
  background: linear-gradient(to right, #4A90E2, #5C6BC0) !important;
}

.review-actions {
  margin-top: 40px;
  display: flex;
  justify-content: center;
  gap: 20px;
}

:deep(.review-actions .el-button) {
  padding: 10px 24px;
  font-size: 16px;
  border-radius: 8px;
}

:deep(.review-actions .el-button--text) {
  color: #f44336;
}

/* 表单提示样式 */
.form-tip {
  font-size: 12px;
  color: #999;
  margin: 5px 0 0 0;
  line-height: 1.4;
}

.upload-tip {
  font-size: 12px;
  color: #999;
  margin: 5px 0 0 0;
}

/* 地址选择器样式 */
.address-selector {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  gap: 10px;
}

.address-preview {
  margin-top: 10px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.address-label {
  font-weight: 500;
  color: #606266;
}

.address-text {
  color: #303133;
  margin-left: 5px;
}

@media (max-width: 768px) {
  .address-selector {
    flex-direction: column;
    align-items: stretch;
  }

  .address-selector .el-select {
    width: 100% !important;
    margin-right: 0 !important;
    margin-bottom: 10px;
  }
}

/* 错误提示样式 */
.error-tip {
  color: #f56c6c;
  font-size: 12px;
  margin-top: 5px;
  line-height: 1.4;
}

.is-error .el-input__inner {
  border-color: #f56c6c;
}

.is-error .el-input__inner:focus {
  border-color: #f56c6c;
  box-shadow: 0 0 0 2px rgba(245, 108, 108, 0.2);
}



/* 房源信息页面布局 */
.house-info-container {
  display: flex;
  gap: 30px;
  align-items: flex-start;
}

.form-section {
  flex: 1;
  min-width: 0;
}

.tips-section {
  flex: 0 0 350px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 配套设施网格布局 */
.facilities-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 15px 20px;
  margin-top: 10px;
}

.facilities-grid .el-checkbox {
  margin: 0;
  white-space: nowrap;
}

.tip-card {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.tip-title {
  font-weight: 600;
  color: #303133;
}

.tip-content p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.tip-content ul {
  margin: 0;
  padding-left: 20px;
}

.tip-content li {
  margin: 6px 0;
  color: #606266;
  font-size: 14px;
  line-height: 1.5;
}

.tip-note {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 15px;
  padding: 10px;
  background-color: #fef7e0;
  border: 1px solid #f5d659;
  border-radius: 6px;
  color: #e6a23c;
  font-size: 13px;
}

@media (max-width: 1200px) {
  .house-info-container {
    flex-direction: column;
  }

  .tips-section {
    flex: none;
    width: 100%;
  }

  .facilities-grid {
    grid-template-columns: repeat(4, 1fr);
  }
}

@media (max-width: 768px) {
  .facilities-grid {
    grid-template-columns: repeat(3, 1fr);
    gap: 10px 15px;
  }
}

@media (max-width: 480px) {
  .facilities-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* 位置信息表单样式 */
.location-form {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

/* 定位按钮样式 */
.location-actions {
  margin-top: 10px;
  text-align: center;
}

.location-actions .el-button {
  margin: 0 5px;
}

/* 地图说明文字样式 */
.map-instructions .warning-text {
  color: #e6a23c;
  font-weight: 500;
  margin-top: 5px;
}

/* 发布操作区域样式 */
.publish-actions {
  margin-top: 30px;
  padding: 20px;
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 8px;
  text-align: center;
}

.publish-actions .el-button {
  margin-bottom: 10px;
}

.publish-tip {
  color: #6b7280;
  font-size: 14px;
  margin: 0;
}

/* 位置信息显示样式 */
.position-info {
  background-color: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 6px;
  padding: 15px;
  margin-top: 10px;
}

.position-info p {
  margin: 5px 0;
  color: #374151;
}

.position-info strong {
  color: #1f2937;
}

/* 图片上传相关样式 */
.image-upload-section {
  padding: 20px;
}

.upload-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
  margin-bottom: 0;
}

.cover-image-selector {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-top: 10px;
}

.cover-image-item {
  position: relative;
  width: 80px;
  height: 80px;
  border: 2px solid #dcdfe6;
  border-radius: 6px;
  cursor: pointer;
  overflow: hidden;
  transition: all 0.3s;
}

.cover-image-item:hover {
  border-color: #409eff;
}

.cover-image-item.active {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.cover-image-item img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.cover-badge {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: rgba(64, 158, 255, 0.9);
  color: white;
  text-align: center;
  font-size: 12px;
  padding: 2px;
}

.cover-tip {
  color: #909399;
  font-size: 12px;
  margin-top: 8px;
  margin-bottom: 0;
}

/* 房产证编号输入框样式 */
.certificate-number-input {
  width: 100%;
}

.new-certification-hint {
  margin-top: 8px;
  display: flex;
  align-items: center;
}

.clear-btn {
  color: #409eff;
  font-size: 12px;
  padding: 4px 8px;
  min-height: auto;
  white-space: nowrap;
  display: flex;
  align-items: center;
  gap: 4px;
}

.clear-btn:hover {
  color: #66b1ff;
  background-color: #f0f9ff;
}

.clear-btn .el-icon {
  font-size: 14px;
}

</style>
